import requests, json


class GetAccess:

    def __init__(self, ak="9jBvknWLKztkaAckXN3REjjn", sk="nFLcQaMgTvF93GR13BwrTX7G1p5ItGEW"):
        url = 'https://aip.baidubce.com/oauth/2.0/token?' \
              'grant_type=client_credentials&' \
              'client_id=%s&' \
              'client_secret=%s' % (ak, sk)

        # 向百度服务器发起一个请求, 获取响应r
        r = requests.post(url=url)
        self.access_token = r.json().get('access_token')


class FaceRegister(GetAccess):

    def face(self, pic, img_type, group_id, user_id, user_info=None):

        url = 'https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add?' \
              'access_token=%s' % self.access_token

        header = {
            "Content-Type": "application/json"
        }

        body = {
            "image": pic,
            "image_type": img_type,
            "group_id": group_id,
            "user_id": user_id,
        }
        if user_info:
            body["user_info"] = user_info

        r = requests.post(url=url, data=body, headers=header)

        return r.json()


# 多张图片进行活体检测
class FaceLive(GetAccess):

    def face(self, image_list, image_type_list, face_field):
        url = "https://aip.baidubce.com/rest/2.0/face/v3/faceverify?" \
              "access_token=%s" % self.access_token

        header = {
            "Content-Type": "application/json"
        }

        body = []
        i = 0
        while i < len(image_list):
            image_dict = {}
            image_dict["image"] = image_list[i]
            image_dict["image_type"] = image_type_list[i]
            image_dict["face_field"] = face_field
            body.append(image_dict)
            i += 1

        body = json.dumps(body)
        r = requests.post(url=url, headers=header, data=body)
        return r.json()






